import base64
import hashlib
import random
from binascii import a2b_hex, b2a_hex

import rsa
from django.shortcuts import HttpResponse

import cmdb.api.http_result as hh
from cmdb import security
from cmdb.security import PyRSA

from cmdb.api.session import session_set
from cmdb.api.session import session_get
import uuid

def request_pk(req):

    step = req.POST.get('step', '1')

    if step == '1':
        # 生成rsa
        keys = security.PyRSA().gen_keys()
        # print(keys[1])
        pri_k = str(b2a_hex(keys[3]))[2: -1]

        k2 = str(keys[2])[2:-1]
        # print('公钥',k2)

        key = base64.b64encode(k2.encode())
        # print(key)
        # 返回key 的 base64
        result = hh.result(1, hh.RESULT_SUCCESS, {'key': key})
        # print(result)

        session_set(key, 'pri_key', pri_k)

        return HttpResponse(result)

    elif step == '2':
        # 客户端传来的public key
        pk = req.POST.get('pk', 'null')
        key = req.POST.get('key', 'null')
        # print('pk: %s'%pk)
        # print('key', key)
        pk = base64.b64decode(pk)
        # 这个pk 为加密过的公钥  使用第一步中服务器传给客户端的公钥进行的加密
        # 解密这个公钥

        # print('session[pri_key] = %s' % pri_key_str)
        pri_key_str = session_get(key, 'pri_key')
        # print('pri_key', pri_key_str)

        if pri_key_str:
            pri_key = PyRSA.parse_private_key(a2b_hex(pri_key_str))
            # print(pri_key)
            # 解密 :  客户端发过来的是用服务器发给客户端的公钥加密后的密文  需要解密得到客户端的公钥(明文)
            pub_key_str = rsa.decrypt(pk, pri_key)
            # print(pub_key_str)

            # 由公钥明文 -> 公钥对象
            pub_key = PyRSA.parse_public_key(pub_key_str)
            # print(pub_key)

            # 生成key
            key = gen_key()
            # print(key)

            # 使用客户端的公钥加密
            key0 = rsa.encrypt(bytes(key, encoding='utf-8'), pub_key)
            key0 = base64.b64encode(key0)
            # print(key0)

            token = uuid.uuid1().__str__()
            session_set(token, 'key', key)
            result = hh.result(1, hh.RESULT_SUCCESS, {'key': key0, 'token': token})
            return HttpResponse(result)
        else:
            return HttpResponse(hh.result(0, 'there is no private key'))

    else:
        return HttpResponse(hh.result(0, 'step is illegal'))




# 生成随机密码 32位
# 随机数的md5
def gen_key():
    rand = random.random()
    # print(rand)
    md = hashlib.md5()
    md.update(str(rand).encode())
    key = md.hexdigest()
    # print(key, type(key))
    return key

